package com.sk.trans.controller;

import com.sk.trans.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOError;
import java.io.IOException;

//2. 声明式
@RequestMapping("/trans")
@RestController
public class TestController {

    @Autowired
    private UserService userService;

    @Transactional(rollbackFor = Exception.class)//自动开启事务(自动提交(程序运行成功)/回滚事务(程序失败时，异常时【默认只有error和RuntimeException才会回滚
    //，可以通过配置Transactional注解的rollbackFor来指定遇到什么样的类型回滚 ))
    @RequestMapping("/register")
    public boolean register(String userName,String password){

        Integer result = userService.insert(userName, password);
        System.out.println("插入用户表,result: "+ result);

        return true;

    }

    @Transactional//异常没有捕获时，事务回滚，异常捕获时，事务提交
    //异常捕获时，如何回滚？ 1.重新抛出异常 2. 手动回滚当前事务(如下)
    @RequestMapping("/register2")
    public boolean register2(String userName,String password){

        Integer result = userService.insert(userName, password);
        System.out.println("插入用户表,result: "+ result);
        try {
            int a = 10/0;
        } catch (Exception e){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return true;

    }

    @SneakyThrows
    @Transactional
    @RequestMapping("/register3")//回滚
    public boolean register3(String userName,String password){

        Integer result = userService.insert(userName, password);
        System.out.println("插入用户表,result: "+ result);
        if (true){
            throw new IOException();
        }
        return true;
    }


    @Transactional
    @RequestMapping("/register4")//事务提交了
    public boolean register4(String userName,String password) throws IOException{

        Integer result = userService.insert(userName, password);
        System.out.println("插入用户表,result: "+ result);
        if (true){
            throw new IOException();
        }

        return true;

    }
}
